"""文本对齐路由模块"""
import os
from typing import List, Dict
from flask import Blueprint, request, jsonify
from werkzeug.utils import secure_filename
from utils.text_aligner import RuleBasedAligner
from models import SentencePair, db
# 导入traceback模块，用于错误追踪
import traceback 

align_bp = Blueprint('align', __name__)

# 配置上传文件夹
UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)


def read_lines(file_path: str) -> List[str]:
    """
    读取文件，返回非空行列表
    
    Args:
        file_path: 文件路径
        
    Returns:
        非空行的列表
    """
    with open(file_path, 'r', encoding='utf-8') as f:
        return [line.strip() for line in f if line.strip()]


def prepare_result_preview(raw_sentences1: List[str], raw_sentences2: List[str], 
                          aligned_pairs: List[Dict], max_preview: int = 50) -> List[Dict]:
    """
    准备对齐结果预览数据
    
    Args:
        raw_sentences1: 第一组原始句子
        raw_sentences2: 第二组原始句子
        aligned_pairs: 对齐结果
        max_preview: 最大预览数量
        
    Returns:
        预览数据列表
    """
    return [
        {
            'text1': raw_sentences1[item['index1']],
            'text2': raw_sentences2[item['index2']],
            'similarity': item['similarity']
        }
        for item in aligned_pairs[:max_preview]
    ]


@align_bp.route('/align', methods=['POST'])
def auto_align():
    """自动对齐两个文本文件中的句子"""
    # 检查请求中是否包含两个文件
    if 'file1' not in request.files or 'file2' not in request.files:
        return jsonify({'error': '需同时上传两个文件'}), 400

    # 获取语言参数
    lang1 = request.form.get('lang1', 'zh')  # 默认中文
    lang2 = request.form.get('lang2', 'vi')  # 默认越南语

    # 验证支持的语言
    supported_languages = {'zh', 'vi', 'th', 'id'}
    if lang1 not in supported_languages or lang2 not in supported_languages:
        return jsonify({'error': f'不支持的语言组合，支持的语言: {", ".join(supported_languages)}'}), 400

    file1 = request.files['file1']  # 第一个语言文件
    file2 = request.files['file2']  # 第二个语言文件

    # 检查两个文件是否都是txt格式
    if not (file1.filename.endswith('.txt') and file2.filename.endswith('.txt')):
        return jsonify({'error': '仅支持 .txt 文件'}), 400
    
    # 保存临时文件
    path1 = os.path.join(UPLOAD_FOLDER, secure_filename(file1.filename))
    path2 = os.path.join(UPLOAD_FOLDER, secure_filename(file2.filename))
    file1.save(path1)
    file2.save(path2)

    try:
        # 读取原始句子
        raw_sentences1 = read_lines(path1)
        raw_sentences2 = read_lines(path2)

        # 验证文件内容
        if not raw_sentences1:
            language_names = {
                'zh': '中文', 'vi': '越南语', 'th': '泰语', 'id': '印尼语'
            }
            lang1_name = language_names.get(lang1, lang1)
            return jsonify({'error': f'{lang1_name}文件为空或无有效句子'}), 400

        if not raw_sentences2:
            language_names = {
                'zh': '中文', 'vi': '越南语', 'th': '泰语', 'id': '印尼语'
            }
            lang2_name = language_names.get(lang2, lang2)
            return jsonify({'error': f'{lang2_name}文件为空或无有效句子'}), 400

        # 执行对齐
        # 传递语言信息给对齐器
        aligner = RuleBasedAligner(lang1=lang1, lang2=lang2)
        # 调用对齐方法，获取对齐的句子对
        aligned_pairs = aligner.align(raw_sentences1, raw_sentences2)

        # 将对齐结果存入数据库
        for item in aligned_pairs:
            # 创建SentencePair模型实例
            pair = SentencePair(
                lang1=lang1,
                text1=raw_sentences1[item['index1']],    # 关键：需记录原始索引
                lang2=lang2,
                text2=raw_sentences2[item['index2']],
                source='auto',
                status='pending'
            )
            # 将实例添加到数据库会话
            db.session.add(pair)
        # 提交数据库事务
        db.session.commit()
        
        # 准备预览数据
        result_preview = prepare_result_preview(raw_sentences1, raw_sentences2, aligned_pairs)

        return jsonify({
            'message': '自动对齐完成',
            'aligned_count': len(aligned_pairs),
            'total1': len(raw_sentences1),
            'total2': len(raw_sentences2),
            'lang1': lang1,
            'lang2': lang2,
            'aligned_pairs': result_preview
        })

    except UnicodeDecodeError:
        db.session.rollback()
        return jsonify({'error': '文件编码错误，请保存为 UTF-8 格式'}), 400
    except Exception as e:
        db.session.rollback()
        traceback.print_exc()  # 👈 这行会把完整错误打印到 VSCode 终端
        return jsonify({'error': f'对齐失败: {str(e)}'}), 500
    finally:
        # 清理临时文件
        for p in [path1, path2]:
            if os.path.exists(p):
                try:
                    os.remove(p)
                except Exception:
                    pass  # 忽略清理文件时的异常